package com.bml.architect.algorithms.complex;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class MyComplexDbAlgorithm implements ComplexKeysShardingAlgorithm<Long> {
    @Override
    public Collection<String> doSharding(Collection<String> collection, ComplexKeysShardingValue<Long> complexKeysShardingValue) {
        //复合分片健，执行的sql是select * from course where user_id=? and cid between ? and ?
        Range<Long> cidRange = complexKeysShardingValue.getColumnNameAndRangeValuesMap().get("cid");
        Collection<Long> userIdValue = complexKeysShardingValue.getColumnNameAndShardingValuesMap().get("user_id");

        Long lowVal = cidRange.lowerEndpoint();
        Long upperVal = cidRange.upperEndpoint();
        System.out.println("上限值为=" + upperVal);
        System.out.println("下限值为="+lowVal);

        List<String> tables = new ArrayList<>();
        for (Long aLong : userIdValue) {
            BigInteger shardingValue = BigInteger.valueOf(aLong);
            BigInteger val = shardingValue.mod(new BigInteger("2")).add(new BigInteger("1"));
            tables.add("m"+val);
        }
        return tables;
    }
}
